<template>
  <div class="config-section">
    <div class="section-header">
      <div class="section-icon">⚙️</div>
      <h2>配置设置</h2>
    </div>
    
    <div class="form-container">
      <div class="form-group">
        <label for="configName">
          <span class="label-icon">📝</span>
          配置名称
        </label>
        <input 
          id="configName" 
          v-model="configName" 
          type="text" 
          placeholder="请输入配置名称"
          class="form-input"
        >
      </div>
      
      <div class="form-group">
        <label for="apiKey">
          <span class="label-icon">🔑</span>
          API 密钥
        </label>
        <div class="input-with-action">
          <input 
            id="apiKey" 
            v-model="apiKey" 
            :type="showApiKey ? 'text' : 'password'" 
            placeholder="请输入 API 密钥"
            class="form-input"
          >
          <button 
            class="toggle-button" 
            @click="showApiKey = !showApiKey"
            type="button"
            :title="showApiKey ? '隐藏密钥' : '显示密钥'"
          >
            <span class="toggle-icon">{{ showApiKey ? '👁️' : '👁️‍🗨️' }}</span>
          </button>
        </div>
        <small class="form-hint">用于访问大语言模型的密钥</small>
      </div>
      
      <div class="form-group">
        <label for="apiUrl">
          <span class="label-icon">🌐</span>
          API 地址
        </label>
        <input 
          id="apiUrl" 
          v-model="apiUrl" 
          type="text" 
          placeholder="请输入 API 端点地址"
          class="form-input"
        >
        <small class="form-hint">默认: https://api.siliconflow.cn/v1/chat/completions</small>
      </div>
      
      <div class="form-group">
        <label for="model">
          <span class="label-icon">🤖</span>
          模型名称
        </label>
        <input 
          id="model" 
          v-model="model" 
          type="text" 
          placeholder="请输入模型名称"
          class="form-input"
        >
        <small class="form-hint">默认: Qwen/Qwen2.5-7B-Instruct</small>
      </div>
    </div>
    
    <div class="button-group">
      <button @click="loadConfig" class="btn btn-secondary">
        <span class="btn-icon">📥</span>
        加载配置
      </button>
      <button @click="saveConfig" class="btn btn-primary">
        <span class="btn-icon">💾</span>
        保存配置
      </button>
    </div>
    
    <div v-if="message" class="message" :class="messageType">
      <span class="message-icon">
        {{ messageType === 'error' ? '❌' : messageType === 'success' ? '✅' : 'ℹ️' }}
      </span>
      {{ message }}
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useConfigStore } from '../store/configStore'

const configStore = useConfigStore()
const configName = ref('头歌考试')
const apiKey = ref('')
const apiUrl = ref('https://api.siliconflow.cn/v1/chat/completions')
const model = ref('Qwen/Qwen2.5-7B-Instruct')
const showApiKey = ref(false)
const message = ref('')
const messageType = ref('')

onMounted(() => {
  // 加载保存的值
  chrome.storage.sync.get(['appConfig', 'modelConfig'], result => {
    if (result.appConfig) {
      configName.value = result.appConfig.name || '头歌考试'
      
      if (result.appConfig.extraConfig) {
        model.value = result.appConfig.extraConfig.model || 'Qwen/Qwen2.5-7B-Instruct'
      }
    }
    
    if (result.modelConfig) {
      apiKey.value = result.modelConfig.apiKey || ''
      apiUrl.value = result.modelConfig.baseUrl || 'https://api.siliconflow.cn/v1/chat/completions'
    }
  })
})

async function loadConfig() {
  if (!configName.value) {
    showMessage('请输入配置名称', 'error')
    return
  }
  
  try {
    showMessage('正在加载配置...', 'info')
    
    // 尝试从服务器加载配置
    await configStore.fetchAppConfig(configName.value)
    
    // 如果有本地 API 密钥，使用它
    if (apiKey.value) {
      updateModelConfig()
      showMessage('配置已加载并更新', 'success')
    } else {
      await configStore.fetchAIModelConfig()
      showMessage('配置已加载', 'success')
    }
  } catch (error) {
    console.error('加载配置失败:', error)
    showMessage(`加载配置失败: ${error.message}`, 'error')
  }
}

function saveConfig() {
  if (!apiKey.value) {
    showMessage('请输入 API 密钥', 'error')
    return
  }
  
  try {
    // 更新应用配置
    const appConfig = {
      name: configName.value,
      extraConfig: {
        model: model.value,
        temperature: 0.3,
        top_p: 0.9
      }
    }
    
    configStore.updateAppConfig(appConfig)
    
    // 更新模型配置
    updateModelConfig()
    
    showMessage('配置已保存', 'success')
  } catch (error) {
    showMessage(`保存配置失败: ${error.message}`, 'error')
  }
}

function updateModelConfig() {
  const modelConfig = {
    apiKey: apiKey.value,
    baseUrl: apiUrl.value,
    name: '自定义模型'
  }
  
  configStore.updateModelConfig(modelConfig)
  
  // 通知内容脚本
  chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
    if (tabs[0]) {
      chrome.tabs.sendMessage(tabs[0].id, {
        from: 'popup',
        action: 'updateConfig',
        data: {
          modelConfig,
          appConfig: {
            name: configName.value,
            extraConfig: {
              model: model.value
            }
          }
        }
      })
    }
  })
}

function showMessage(text, type = 'info') {
  message.value = text
  messageType.value = type
  
  // 3秒后自动清除消息
  setTimeout(() => {
    if (message.value === text) {
      message.value = ''
    }
  }, 3000)
}
</script>

<style>
.config-section {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.section-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 2px solid rgba(102, 126, 234, 0.1);
}

.section-icon {
  font-size: 20px;
}

.section-header h2 {
  font-size: 16px;
  font-weight: 600;
  margin: 0;
  color: #2c3e50;
}

.form-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.form-group label {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  font-weight: 500;
  color: #2c3e50;
}

.label-icon {
  font-size: 14px;
}

.form-input {
  width: 100%;
  padding: 10px 12px;
  border: 2px solid #e1e8ed;
  border-radius: 8px;
  font-size: 14px;
  background: rgba(255, 255, 255, 0.9);
  transition: all 0.2s ease;
}

.form-input:focus {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
  background: white;
}

.input-with-action {
  display: flex;
  gap: 8px;
  align-items: stretch;
}

.input-with-action .form-input {
  flex: 1;
}

.toggle-button {
  padding: 0 12px;
  background: #f8f9fa;
  border: 2px solid #e1e8ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.toggle-button:hover {
  background: #e9ecef;
  border-color: #667eea;
}

.toggle-icon {
  font-size: 16px;
}

.form-hint {
  font-size: 12px;
  color: #6c757d;
  margin-top: 4px;
  line-height: 1.4;
}

.button-group {
  display: flex;
  gap: 12px;
  margin-top: 20px;
}

.btn {
  flex: 1;
  padding: 12px 16px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  transition: all 0.2s ease;
}

.btn-primary {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.btn-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.btn-secondary {
  background: #f8f9fa;
  color: #495057;
  border: 2px solid #e1e8ed;
}

.btn-secondary:hover {
  background: #e9ecef;
  border-color: #667eea;
  color: #667eea;
}

.btn-icon {
  font-size: 14px;
}

.message {
  margin-top: 16px;
  padding: 12px;
  border-radius: 8px;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
}

.message.error {
  background: linear-gradient(135deg, #ff6b6b, #ee5a52);
  color: white;
  box-shadow: 0 4px 12px rgba(255, 107, 107, 0.3);
}

.message.success {
  background: linear-gradient(135deg, #51cf66, #40c057);
  color: white;
  box-shadow: 0 4px 12px rgba(81, 207, 102, 0.3);
}

.message.info {
  background: linear-gradient(135deg, #74c0fc, #339af0);
  color: white;
  box-shadow: 0 4px 12px rgba(116, 192, 252, 0.3);
}

.message-icon {
  font-size: 16px;
}
</style> 